package com.lineage.server.timecontroller.pc;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.thread.PcOtherThreadPool;
import com.lineage.server.world.World;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ExpTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(ExpTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 500;
    this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this, 500L, 500L);
  }
  
  public void run() {
    try {
      Collection<L1PcInstance> all = World.get().getAllPlayers();
      if (all.isEmpty())
        return; 
      Iterator<L1PcInstance> iter = all.iterator();
      while (iter.hasNext()) {
        L1PcInstance tgpc = iter.next();
        if (check(tgpc)) {
          tgpc.onChangeExp();
          Thread.sleep(1L);
        } 
      } 
    } catch (Exception e) {
      _log.error("EXP更新处理时间轴异常重启", e);
      PcOtherThreadPool.get().cancel(this._timer, false);
      ExpTimer expTimer = new ExpTimer();
      expTimer.start();
    } 
  }
  
  private static boolean check(L1PcInstance tgpc) {
    try {
      if (tgpc == null)
        return false; 
      if (tgpc.getOnlineStatus() == 0)
        return false; 
      if (tgpc.getNetConnection() == null)
        return false; 
      if (tgpc.isTeleport())
        return false; 
      if (tgpc.getExp() == tgpc.getExpo())
        return false; 
    } catch (Exception e) {
      return false;
    } 
    return true;
  }
}
